<template>
    <a-drawer
            :visible="formVisible"
            :width="500"
            unmount-on-close
            :title="isEdit ? '编辑' : '新增'"
            @ok="submit"
            @cancel="handleCancel"
    >
        <div>
            <a-form
                    ref="formRef"
                    :model="form"
                    :label-col-props="{ span: 8 }"
                    :wrapper-col-props="{ span: 16 }"
            >
                <a-form-item field="parentId" label="上级部门"   v-if="!isEdit">
                    <a-tree-select
                            v-model="form.id"
                            :data="renderData"
                            placeholder="请选择上级部门"
                    />
                </a-form-item>
                <a-form-item field="name" label="部门名称"
                             :rules="[{required:true,message:'name is required'},{minLength:5,message:'must be greater than 5 characters'}]"

                >
                    <a-input v-model="form.name" placeholder="请填写部门名称" />
                </a-form-item>
            </a-form>
        </div>
    </a-drawer>
</template>

<script lang="ts" setup>
    import { ref, watch, computed ,defineProps } from 'vue';
    import {addDepartments, departmentInfo, editDepartments} from "@/api/system";
    import {Message} from "@arco-design/web-vue";


    const props = defineProps({
        visible: {
            type: Boolean,
            default: false,
        },
        selected: {
            type: String,
            default: "6",
        },
        refreshList: {
            type: Boolean,
            default: false,
        },
        formData: {
            type: Object,
            default: () => {
                return {};
            },
        },
        fetchData :{
            type:Function,
            default: () => {
                return {};
            },
        }
        
        
        /*
        
        renderData: {
            type:Object,
            default: () => {
                return {};
            },
        },*/
    });


    const formRef = ref();//声明才能绑定，  ref="formRef"相当于一个标识可以调用或者检验form的内容

    // 初始数据
    const initData = () => {
        return {
            name: 'eeeeeeee',
        };
    };
    /**
     * 菜单数据
     */
    const form = ref(props.formData);
    // const renderData = ref(props.renderData);

    const renderData = ref([]);
    const data=departmentInfo().then((res)=>{
        // console.log(res.data)
        renderData.value=convertData(res.data);
        // console.log(renderData);
    })



    function convertData(menuList:any) {
        return menuList?.map((item) => {
                const {
                    id,
                    pid,
                    name,
                }=item;
                const son = item.son ?? [];
                const isChild = son != null && son.length !== 0;
                const currentArray: any = {
                    key:id,
                    pid:pid,
                    title:name,
                    children: [],
                }
                // 是否有子菜单，并递归处理
                if (isChild) {
                    currentArray.children = convertData(
                        son,
                    );
                }
                return currentArray;
            }
        )
    }

    const selected = ref(props.selected);
    // console.log(selected);





    const emit = defineEmits<{
        (e: 'update:visible', v: boolean): void;
        (e: 'refresh'): void;
    }>();
    const formVisible = ref(false);




    // 判断是编辑还是新增
    // console.log(form.value.id);
    const isEdit = computed(() => !!form.value.key);
    // console.log(isEdit);



    const submit = async () => {
        formVisible.value = true;
        const validate = await formRef.value.validate();
        // console.log(formRef.value);
        // console.log(validate);

        if (!validate) {
            // console.log(isEdit.value);
            if (isEdit.value) {
                // console.log(form.value);
                let data={
                    id:form.value.key,
                    name:form.value.name
                }
                await editDepartments(data).then(() => {
                    props.fetchData()
                    Message.success("修改成功");
                    // console.log("修改成功")
                });

            } else {
                // console.log(form.value);
                let data={
                    pid:form.value.id,
                    name:form.value.name
                }
                // console.log(data);
                await addDepartments(data).then(() => {
                    props.fetchData()
                    Message.success("添加成功");
                    // console.log("添加成功")
                });

            }
            // console.log(initData);
            form.value = { ...initData };
            // console.log(form.value);
            formVisible.value = false;
            emit('refresh');
        }
    };

    const handleCancel = () => {
        formVisible.value = false;
        form.value = { ...initData };
    };

    watch(
        () => formVisible.value,
        (val) => {
            emit('update:visible', val);
        }
    );

    watch(
        () => props.visible,
        (val) => {
            formVisible.value = val;
        }
    );

    watch(
        () => props.formData,
        (val) => {
            form.value = val;
        }
    );
    // watch(
    //     () => props.renderData,
    //     (val) => {
    //         renderData.value = val;
    //     }
    // );
</script>
